package P3排序算法;

import java.util.Arrays;
//单轴三路快速排序
public class QuickSort03 {
    public static void main(String[] args) {
        int[] arr = {4, 2, 3, 1, 2, 4, 2, 4, 3, 7, 5, 6, 3, 5, 3, 3, 4, 3, 4, 6, 7, 9, 4, 5, 4};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        swap(arr, l, (int) (Math.random() * (r - l + 1) + l));
        int v = arr[l];
        int lt = l;     //[l+1,lt] < v
        int gt = r + 1; //[gt,r] > v
        int i = l + 1;  //[lt+1,gt-1] == v [lt+1,i) == v
        while (i < gt) {
            if (arr[i] < v) {
                swap(arr, lt + 1, i);
                lt++;
                i++;
            } else if (arr[i] > v) {
                swap(arr, i, gt - 1);
                gt--;
            } else {
                i++;
            }
        }
        swap(arr, l, lt);
        quickSort(arr, l, lt - 1);
        quickSort(arr, gt, r);
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}